package lock.deadlock;

import java.util.concurrent.TimeUnit;

/**
 * @program: algorithm
 * @description: 死锁案例
 * @author: 陈恩涛
 * @create: 2022-08-11 11:14
 **/
public class DeadLockDemo {
    public static void main(String[] args) {
        final Object o1 = new Object();
        final Object o2 = new Object();

        new Thread(() -> {
            synchronized (o1) {
                System.out.println("线程A获取到锁1");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程A尝试去获取锁2");
                synchronized (o2) {
                    System.out.println("线程A获取到锁2");
                }
            }
        },"A").start();

        new Thread(() -> {
            synchronized (o2) {
                System.out.println("线程B获取到锁2");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程B尝试去获取锁1");
                synchronized (o1) {
                    System.out.println("线程A获取到锁1");
                }
            }
        },"B").start();
    }
}
